import base64
import hashlib
from datetime import datetime
from io import BytesIO

import qrcode


class CommonUtils(object):
    """
    注意这个类不需要Odoo的Env环境
    """

    def generate_qr_code(self, link):
        """
        生成二维码
        Params:
        -link:链接
        """
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(link)
        qr.make(fit=True)
        img = qr.make_image(fill='black', back_color='white')
        byte_stream = BytesIO()
        img.save(byte_stream)
        binary_data = byte_stream.getvalue()
        # 使用base64模块对二进制数据进行编码
        base64_data = base64.b64encode(binary_data).decode('utf-8')
        return base64_data

    def gene_random_sequence(self):
        """
        生成随机序列
        """
        # 生成随机序列
        timestamp = datetime.now().timestamp()
        md5_obj = hashlib.md5()
        md5_obj.update(str(timestamp).encode('utf-8'))
        md5_hex = md5_obj.hexdigest()
        return md5_hex

    def always_ceil(self, value, decimal_places=0):
        """
        保留几位小数时，总是进一
        """
        multiplier = 10 ** decimal_places
        temp = value * multiplier
        rounded_temp = int(temp) + 1
        rounded_value = rounded_temp / multiplier
        return rounded_value
